"use strict";

/**
 * 日志收集中间件
 */


var Router = require('koa-router');
var appUtil = require('../common/app_utils.js');

var __pathPrefix = '/'; // 所有请求都需要 log中间件
appUtil.appLog('router:' + __pathPrefix);
var router = new Router({prefix: __pathPrefix});

router.all('**', function*(next) {
  // collect log
  this.startAt = new Date();
  yield next;
  __collect.call(this);
});


function __collect() {
  var logInfo = {};
  var req = this.req;
  var fromIp = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
  logInfo.fromIp = fromIp;
  logInfo.url = decodeURIComponent(this.originalUrl);
  logInfo.method = this.req.method;
  logInfo['X-Response-Time'] = new Date() - this.startAt;
  logInfo.agent = 'faceApi';
  logInfo.startAt = this.startAt;

  var fields = this.request.inParams.fields;
  for (var key of Object.keys(fields)) {
    if (key != 'token')
      logInfo[key] = fields[key];
  }

  // result
  logInfo.status = this.status;
  logInfo.errCode = this.body.errCode;
  logInfo.errMsg = this.body.errMsg;

  appUtil.appLog(logInfo);
  // TODO save to redis then logstash
}
module.exports = router.routes();